/**
 * Created by CN7817 on 2015/12/18.
 */
    $.extend({

        alert:function(msg,callback){
            zk_alert_msg(msg,0,callback)
        },
        /**
         * 显示错误信息
         * @param target
         * 在该目标之后插入错误消息
         * @param msg
         * 消息内容
         * @param time
         * 显示时间，-1表示一直显示
         */
        error:function(target,msg,time){
            var span=$(target).focus().next("span.validate_error");
            if(span.size()==0){
                span= $('<span class="validate_error" style="">'+msg+'</span>').insertAfter(target);
            }else{
                span.text(msg);
            }
            time=time==undefined?3000:time;
            //console.log(time);
            if(time>0){
                setTimeout(function(){
                    span.slideUp(function(){
                        $(this).remove();
                    });
                },time);
            }
        },
        removeError:function(target){
            $(target).next("span.validate_error").remove();
        }
    });
// 统一弹出提示，并可以跳转到上一步
var goback_alert_msg = function(msg,url,callback){
    var html = '<div class="popbox">';
    html += '<div class="pop-m"><p>'+msg+'</p></div>';
    html += '<div class="pop-btnbox"><a class="pop-fh" href="'+url+'">返回上一步</a></div></div>';
    layer.open({
        area: ['80%','120px'],
        type:1,
        title: false,
        content: html,
        closeBtn: 0,
        yes:callback
    });
}
// 全局的弹出框提示(有传time=0就要点击空白出消失，如果不传就会在3消失时间)
var zk_alert_msg = function(msg,time,callfun){
    time = time==undefined?3000:time*1000;
    var index=layer.msg(msg,{
        shadeClose: true,
        shade: 0.6,
        time:time
    });
    if(callfun){
        setTimeout(function(){
            layer.close(index);
            callfun();
        },1000);
    }
};
var zk_default_alert_msg=function(msg){
    layer.open({
        content: msg,
        time:2
    });
};
// 统一弹出询问框
var zk_confirm_msg = function(msg,y_call,n_call){
    var index=layer.open({
        title: ['温馨提示','background-color:#46c1d6; color:#fff; text-align:center;'],
        content:msg,
        shadeClose:false,
        btn: ['确认', '取消'],
        yes: function(){
            layer.close(index);
            if(y_call){
                y_call();
            }
        },
        no: function(){
            layer.close(index);
            if(n_call){
                n_call();
            }
        }
    });
};
// 处理轨迹
var TrackClass = function () {
    var track = function () {
        this.paths = [];
        this.withOuts = ["order.html", "login.html","dz_res.html","account_confirm.html","reset_mob.html","modify_pwd.html"];
    };
    document.createElement("meta")
    track.prototype.key = "trackPaths";
    track.prototype.step = function (path) {
        if (!path) {
            return 0;
        }
        var step = 0;
        if (this.is_ignore(path)) {
            for (var i = 0; i < this.paths.length; i++) {
                if (path == this.paths[i]) {
                    path = this.paths[i - 1];
                    break;
                }
            }
            return step += 1 + this.step(path);
        }
        return step;
    }
    track.prototype.back = function () {

        this.paths = this.getPaths();

        if (!this.paths || this.paths.length == 0) {
            window.location = __indexUrl__?__indexUrl__:"/";
            return;
        }
        var i = this.paths.length - 2;
        if(this.paths[i+1]!=location.href){
            i++;
        }
        var path = this.paths[i];
        var step = this.step(path);
        if (step != 0) {
            path = this.paths[i - step];
        }
        if (!path) {
            window.location.href = __indexUrl__?__indexUrl__:"/";
            return;
        }
        this.paths.splice(i, 2);
        this.save();
        window.location.href = path;
    }
    track.prototype.save = function () {
        var strpaths = "";
        for (var i = 0; i < this.paths.length; i++) {
            if (i > 0) {
                strpaths += ",";
            }
            strpaths += this.paths[i];
        }
        window.sessionStorage.setItem(this.key, strpaths);
    }
    track.prototype.is_ignore=function(path){
        for (var i = 0; i < this.withOuts.length; i++) {
            //var paths=path.split(/(\/)|(\\)/);
            //paths=paths.pop();
            var reg=new RegExp(this.withOuts[i]+"$");
            if (reg.test(path)) {
                return true;
                break;
            }
        }
        return false;
    }
    track.prototype.addPath = function (path) {
        //去掉参数部分
        if (path.indexOf("?") > 0) {
            path = path.substring(0, path.indexOf("?"));
        }
        this.paths = this.getPaths();
        var added = false;
        var index = 0;
        for (var i = 0; i < this.paths.length; i++) {
            if (path == this.paths[i]) {
                added = true;
                index = i;
                break;
            }
        }
        if (added) {
            this.paths.splice(index, 1);
        }
        //var without = false;
        if (!this.is_ignore(path)) {
            this.paths.push(path);
            this.save();
        }
    }
    track.prototype.getPaths = function () {
        var strpaths = window.sessionStorage.getItem(this.key);
        strpaths = strpaths || "";
        this.paths = strpaths.split(",");
        if (!this.paths || this.paths == "") {
            this.paths = [];
        }
        return this.paths;
    }
    track.prototype.init = function () {
        var path = window.location.href;
        this.addPath(path);
    }
    var t = new track();
    t.init();
    return t;
}
// 定义一个轨迹
var track = new TrackClass();

// 给JS的数组对象定义一个函数，用于查找指定的元素在数组中的位置，即索引，
Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
// 通过上面的方法得到这个元素的索引，使用js数组自己的函数去删除这个元素
Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
        return true;
    }else{
        return false;
    }
};
// 成员列表显示
var show_cy = function(){
    $('.cy-list').slideDown('slow');
};
// 验证手机
var zk_verify_mobile = function(str){
    var re = /^1[34578]\d{9}$/;
    return re.test(str);
};
// 校验密码：只能输入6-20个字母、数字、下 划线
var zk_is_pwd = function(pwd){
    var reg = /^(?![^a-zA-Z]+$)(?!\D+$).{6,20}$/;
    return reg.test(pwd);
};

// 判断是否是手机
var ismob = function() {
    ///<summary>判断请求是否来自手机、平板等</summary>
    var match = navigator.userAgent.match(/(iphone|iPod|iPad|android|ios|windows phone)/i);
    return match != null;
};
// PC、手机事件映射
var eventMap = function(event,namesplace){
    //namesplace提供了绑定事件的命名空间，可以防止意外解绑非目标事件处理程序
    namesplace=namesplace?'.'+namesplace:"";
    event_maps={"click":"touchend","mousemove":"touchmove","mousedown":"touchstart","mouseup":"touchend"}
    if(ismob() && event_maps[event])
        event=event_maps[event];
    return event+namesplace;
};

var dataLoading = function(){
    layer.load(0, {
      shade: [0.5,'#000'],
      content:'<div class="loading-box"><div class="loading-bg"></div><div class="loading-active-bg"></div></div>'
    });
    
};
var removeDataLoading = function(){
    layer.closeAll('loading');  
};

$(function(){
    //处理发送手机验证码
    $(document).on(eventMap("click"),"[data-role='mobVCode']",function(e){
        e.preventDefault();
        var sender=$(this);
        if(sender.attr("disabled")){
            return;
        }
        var mob=$(sender.attr("data-mob")).val() || "";
        if(!$.validator.is_mob(mob)){
            $.error(sender.attr("data-mob"),"请输入正确的手机号码");
            return;
        }
        //var text1=sender.attr("data-text") || "发送验证码";
        var text2=sender.attr("data-text2") || "{time}秒后重新获取";
        var text3=sender.attr("data-text3") || "重新发送";
        var time=parseInt( sender.attr("data-time") || '60');
        $.ajax({
            url:(__root__?__root__:"/")+"Share/send_mobile_vcode",
            dataType:"json",
            type:"get",
            data:{"mob":mob},
            beforeSend:function(){
                sender.attr({disabled:"disabled"}).css({backgroundColor:"#9c9c9c"});
            },
            success:function(res){
                if(res.status==1){
                    //开始计时
                    var t=text2.replace("{time}",time);
                    sender.text(t).val(t);
                    var h=setInterval(function(){
                        t=text2.replace("{time}",--time);
                        sender.text(t).val(t);
                        if(time==0){
                            clearInterval(h);
                            sender.removeAttr("disabled").css({backgroundColor:""}).text(text3).val(text3);
                        }
                    },1000);
                }else{
                    $.alert(res.msg);
                    sender.removeAttr("disabled").text(text3).val(text3);
                }
            },
            error:function(){
                sender.removeAttr("disabled").text(text3).val(text3);;
            }
        });
    });
     // 返回上一页
    $('#btn_common_go_back').on(eventMap('click'),function(e){
        e.preventDefault();
        track.back();
    });

    //处理抽屉
    $(document).on(eventMap("click"), "[data-role='drawer']", function () {
        //if(Math.abs(moveing_e_y-moving_s_y)>20){//非左键则不处理{
        //    return;
        //}
        var sender = $(this);
        var panel = sender.attr("data-panel");
        if (!panel) {
            return;
        }
        var scroll=sender.attr("data-scroll") || "auto";
        panel = $(panel);
        var fixed = sender.attr("data-fixed");
        if (!fixed) {
            fixed = "left";
        }
        var mask = sender.attr("data-mask") || "none";
        if (mask=="auto") {
            mask = "<div id='drawermask' class=\"leftmask\" style='width:100%;height:100%;position:absolute;top:0;left:0;'></div>";
            $(mask).appendTo("body").height($(document).height());
            sender.attr("data-mask", "#drawermask");
        }
        var zindex = 100000;
        mask = $(mask).css({ zIndex: (zindex - 1) });
        var position=sender.attr("data-position") || "absolute";
        var style={ position: position, zIndex: zindex};
        if(fixed!="bottom"){
            style.top=0;
        }
        panel.css(style);

        var handle = sender.attr("data-handle");
        if (!handle) {
            handle = mask;
        } else {
            handle = $(handle);
        }
        var visible = Number(sender.attr("data-visible"));
        if (!visible) {
            visible = 0;
            sender.attr("data-visible", 0);
        }
        var time = 500;
        var win=$(window);
        var w_w=win.width();
        var w_h=win.height();
        var pw = (fixed=="left" || fixed=="right" ?Math.max(panel.width(),w_w):Math.max(panel.height(),w_h));
        var mw = (fixed=="left" || fixed=="right" ?Math.max(mask.width(),w_w):Math.max(mask.height(),w_h));
        var t = time * pw / mw;
        var offset = mw - pw;
        var step = 20;

        if (visible == 0) {
            var data={display: "block",opacity:0};
            data[fixed]=-pw;
            panel.css(data);
            data[fixed]=-mw;
            mask.css(data);
            data={opacity:1};
            data[fixed]=0;
            panel.animate(data, time);
            mask.animate(data, t);
        }
        handle.unbind(eventMap("click")).on(eventMap("click"), function (e) {
            e.preventDefault();
            var data={opacity:0};
            data[fixed]=-pw;
            panel.animate(data, time, function () {
                $(this).hide();
            });
            data[fixed]=-mw
            mask.animate(data, t, function () {
                $(this).hide();
            });
        });
        var callback=sender.attr("data-callback");
        if(callback){
            callback=eval(callback);
        }else{
            callback=function(){};
        }
        if($.isFunction(callback)){
            callback.call(this);
        }
        //如果是手机的话，去掉window滑动事件,抽屉的滑动由代码实现
        if(ismob() && scroll=="auto"){
            var b_y= 0,p_y= 0,e_y= 0,b_time=0;
            var h=null;
            panel.on("touchstart",function(e){
                e= e.originalEvent.targetTouches[0];
                b_y= e.clientY;
                p_y=panel.scrollTop();
                b_time=(new Date()).getTime();
                if(h){
                    clearInterval(h);
                }
            }).on("touchmove",function(e){
                //e.preventDefault();
                var t= e.originalEvent.targetTouches[0];
                e_y= t.clientY;
                panel.scrollTop(p_y-(e_y-b_y));
                //e.preventDefault();
            }).on("touchend",function(e){
                //e.preventDefault();
                var e_time=(new Date()).getTime();
                var t_off=e_time-b_time;
                if(t_off<300 && Math.abs(e_y-b_y)>100){
                    //console.log(t_off);
                    //如果滑动时间小于600毫秒，则启用快速滑动功能
                    var b_t=panel.scrollTop();
                    var d=e_y-b_y;//方向
                    d=d/Math.abs(d);
                    var distance=d>0?panel[0].scrollHeight-b_t:b_t;
                    var drag=10;//阻力
                    var speed=distance/drag;//速度
                    if(h){
                        clearInterval(h);
                    }
                    h=setInterval(function(){
                        distance-=speed;
                        b_t-=d*speed;
                        panel.scrollTop(b_t);
                        //console.log(b_t+"___"+speed+"________"+distance);
                        if(speed==0 ||distance<=0){
                            clearInterval(h);
                        }else{
                            speed=distance/drag;
                            speed=speed>0?Math.floor(speed):Math.ceil(speed);
                        }
                    },50);
                }
            });

        }

    });

    var moving_s_y=0;//判断当前是否在滚动，如果是，则相应使用touchend绑定的事件，不应继续处理
    var moveing_e_y=0;
    //处理tab
    $("[data-role='tab']",document).each(function(){
        var tab=$(this);
        var visible = Number( tab.attr("data-visible") || "-1");//显示哪个tab_panel，-1表示都不显示
        var animate = tab.attr("data-animate");
        var callback = getCallbackFun(tab);
        var toggle = Number(tab.attr("data-toggle") || "1");//自身是否作为开关使用
        var onClass = tab.attr("data-class") || "onclass";
        var offClass="";
        if(onClass){
            onClass=onClass.split(",");
            if(onClass.length>1 && onClass[1]!=""){
                offClass=onClass[1];
                onClass=onClass[0];
            }else{
                onClass=onClass[0];
            }
        }
        if(visible==-1){
            tab.find("[data-role='tab_head']").removeClass(onClass).addClass(offClass).each(function(){
                $($(this).attr("data-panel")).hide();
            });
        }else{
            tab.find("[data-role='tab_head']").removeClass(onClass).addClass(offClass).each(function(){
                $($(this).attr("data-panel")).hide();
            });
            $(tab.find("[data-role='tab_head']").eq(visible).removeClass(offClass).addClass(onClass).attr("data-panel")).show();
        }
        //全部显示
        if(visible==-2){
            tab.find("[data-role='tab_head']").removeClass(onClass).addClass(offClass).each(function(){
                $($(this).attr("data-panel")).show();
            });
        }
        //给加上索引
        tab.find("[data-role='tab_head']").each(function(i){
            $(this).attr("data-index",i);
        });
        $(this).on(eventMap("click"), "[data-role='tab_head']", function (e) {
            e.preventDefault();
            if(Math.abs(moveing_e_y-moving_s_y)>20){//非左键则不处理
                return;
            }
            var sender = $(this);
            var panel = $(sender.attr("data-panel"));
            var index=sender.attr("data-index");
            var ori_index=tab.find("[data-role='tab_head']."+onClass).attr("data-index");
            //将当前项点亮
            var obj=null;
            tab.find("[data-role='tab_head']:not(:eq("+index+"))").removeClass(onClass).addClass(offClass).each(function(){
                obj=$($(this).attr("data-panel"));
                if(animate=="slide")
                    obj.slideUp();
                else{
                    obj.hide();
                }
            });
            obj=$(sender.attr("data-panel"));
            if(index==ori_index && toggle){
                //当点击的是当前选中项时，则反转开关
                sender.addClass(offClass).removeClass(onClass);
                if(animate=="slide")
                    obj.slideUp();
                else{
                    obj.hide();
                }
            }else{
                sender.addClass(onClass).removeClass(offClass)
                if(animate=="slide")
                    obj.slideDown();
                else{
                    obj.show();
                }
            }
            callback.call(this, e);
        });
    });


});

//获取标签中指定的回调函数实例
function getCallbackFun(sender) {
    var strcallback = sender.attr("data-callback");
    function callback(e) {
        return true;
    };
    if (strcallback) {
        try{
            callback = eval(strcallback);
            if(typeof(callback)!="function")
                return function(){return true;};
        }catch(ex){
            return function(){return true;}
        }

    }
    return callback;
}

//滚动加载下一页
var ScrollAutoPage= function(pagecount, url, pagination, list,panel,isasync,callback){
    isasync=isasync||false;//是否同步
    panel=panel||window;
    var pageindex = 2;
    var loading = false;
    if (pageindex - 1 < parseInt(pagecount)) {
        pagination.show();
    }
    $(pagination).on('click',function(){
        if (pageindex - 1< parseInt(pagecount)) {
            addload();
        }
    });
    $(panel).on("scroll", function () {
        if (pageindex - 1 >= parseInt(pagecount)) {
            is_scroll=false;
            pagination.text('到底了....');
            pagination.fadeOut(2000);
            return;
        }

        var fenge = pagination.offset().top;
        if(panel!=window){
            fenge=fenge-$(panel).offset().top;
        }

        var scrolltopp = $(this).scrollTop() + $(panel).height();
        if (scrolltopp > fenge && !loading) {
            addload();
        }
    })

    var addload=function(){
        $.ajaxSettings.async = isasync;
        $.ajax({
            type: 'get',
            url: url,
            dataType: 'json',
            data: {'pageindex': pageindex},
            success: function (res) {
                if (res.status == 1) {
                    if (callback && $.isFunction(callback)) {
                        callback(res);
                    }
                    else
                        list.append(res.info);
                    pageindex++;
                }
            },
            complete: function () {
                loading = false;
            },
            beforeSend: function () {
                loading = true;
            }
        });
    };
}

// 如果是微信的才处理
var __access_type__=""
if(__access_type__ == 'weixin'){
    //微信处理模块
    wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: __appId, // 必填，公众号的唯一标识
        timestamp: __timestamp, // 必填，生成签名的时间戳
        nonceStr: __nonceStr, // 必填，生成签名的随机串
        signature: __signature,// 必填，签名，见附录1
        jsApiList: [ 'checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'hideMenuItems',
            'showMenuItems',
            'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem',
            'translateVoice',
            'startRecord',
            'stopRecord',
            'onRecordEnd',
            'playVoice',
            'pauseVoice',
            'stopVoice',
            'uploadVoice',
            'downloadVoice',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'getNetworkType',
            'openLocation',
            'getLocation',
            'hideOptionMenu',
            'showOptionMenu',
            'closeWindow',
            'scanQRCode',
            'chooseWXPay',
            'openProductSpecificView',
            'addCard',
            'chooseCard',
            'openCard' ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    });

    wx.ready(function(){
        wx.checkJsApi({
            jsApiList: ['chooseImage'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
            success: function(res) {
                if( ! res.checkResult.chooseImage){
                    zk_alert_msg('您好，您当前客户端版本不支持微信的高级功能使用，请先升级您的浏览器或者微信');return;
                }
                // 以键值对的形式返回，可用的api值true，不可用为false
                // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
            }
        });
        wx.error(function(res){
            //zk_alert_msg('监测到您的页面加载有异常,请刷新后重试');return;
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        });
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
    });
}